package com.glodon.paas.account.sdk.sso.web;

import com.glodon.paas.consts.StringConst;
import com.glodon.paas.util.HttpUtils;
import org.apache.http.HttpStatus;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * abstract single sign on web filter
 *
 * @author Don Li
 */
abstract public class AbstractCasSingleSignOnFilter implements Filter {

    public static final String CAS_ASSERTION = "cas_assertion";
    public static final String CAS_SERVICE_TICKET = "cas_service_ticket";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        // check if user is login
        HttpSession session = httpReq.getSession(false);
        Assertion assertion = (session == null) ? null : (Assertion) session.getAttribute(CAS_ASSERTION);
        if (assertion != null) {
            handleSuccess(httpReq, httpResp);
            chain.doFilter(request, response);
            return;
        }
        // todo remove this dependency
        if(HttpUtils.isAjaxRequest(httpReq)){
        	httpResp.setStatus(HttpStatus.SC_UNAUTHORIZED);
    		httpResp.getOutputStream().print(StringConst.LOGOUT);
    	}
    	else{
    		httpResp.sendRedirect(httpReq.getContextPath() + "/index");
    	}
        // not login, then send user to the login page
//        httpResp.sendRedirect(httpReq.getContextPath() + "/index");
    }

    @Override
    public void destroy() {
    }

    /**
     * Handle successful authentication
     *
     * @param request  request
     * @param response response
     */
    abstract protected void handleSuccess(HttpServletRequest request, HttpServletResponse response);
}
